//
//  SYJTabbar.swift
//  weibo
//
//  Created by 孙英建 on 16/4/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class SYJTabbar: UITabBar {

   // 定义一个闭包
    var postbuttonclick: (() -> ())?
    
    
    // 重写init方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        addSubview(composeButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    
    // 懒加载按钮
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        // 背景
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        
        // 图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        button.sizeToFit()
        
        // button的点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
    
    
    // 布局
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
        
        // 设置tabbar的frame
        
        let width = UIScreen.mainScreen().bounds.width / 5
        var index: CGFloat = 0
        
        for value in self.subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                value.frame.origin.x = width * index
                
                value.frame.size.width = width
                
                if index == 1 {
                    index+=1
                }
                index++
            }
        }
    }
    

    // button的点击事件
    func composeButtonClick(){
       self.postbuttonclick?()
    }
    
    
    
}














